// internal/service/fileservice.go
package service

import (
	"context"
	"errors"
	"io"
	"time"

	"gdrive/internal/model"
	"gdrive/internal/repository"
	"gdrive/pkg/storage"

	"github.com/jmoiron/sqlx"
)

// FileService 定义文件业务逻辑接口
type FileService interface {
	Upload(ctx context.Context, userID, filePath string, data io.Reader, size int64, mimeType string) error
	ListFiles(ctx context.Context, userID, path string) ([]*model.File, error)
	// 其他方法...
}

// 实现结构体
type fileService struct {
	repo    repository.FileRepository
	storage storage.StorageClient
}

// NewFileService 创建 FileService 实例
func NewFileService(db *sqlx.DB, storage *storage.MinIOStorage) FileService {
	return &fileService{
		repo:    repository.NewFileRepository(db),
		storage: storage,
	}
}

func (s *fileService) Upload(ctx context.Context, userID, filePath string, data io.Reader, size int64, mimeType string) error {

	data_bufs := make([]byte, 1024)
	if _, err := data.Read(data_bufs); err != nil {
		return errors.New("read data err: " + err.Error())
	}

	if err := s.storage.UploadFile(ctx, filePath, data_bufs); err != nil {
		return errors.New("uploadFile err: " + err.Error())
	}
	// TODO: 检查用户配额
	// TODO: 生成唯一文件 ID（UUID）
	// TODO: 将文件保存到 MinIO，key = uuid
	// TODO: 将元数据插入 PostgreSQL
	return s.repo.CreateFile(ctx, &model.File{
		ID:        generateUUID(),
		Name:      extractFileName(filePath),
		Path:      filePath,
		Size:      size,
		MIMEType:  mimeType,
		CreatedAt: time.Now(),
		UpdatedAt: time.Now(),
	})
}

func (s *fileService) ListFiles(ctx context.Context, userID, path string) ([]*model.File, error) {
	return s.repo.GetFilesByPath(ctx, userID, path)
}
